package com.basic.bio.chat.singlechat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Description:
 * @Date: 2024-03-29 10:30
 * @Author: wz
 **/
public class Server {

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(8888);
            //等待客户端连接
            System.out.println("等待客户端连接。。。");
            //获取客户端的连接
            Socket socket = ss.accept();
            System.out.println("客户端连接成功");
            Scanner scanner = new Scanner(System.in);
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            PrintStream writer = new PrintStream(socket.getOutputStream());
            //客户端先发消息，对应服务端就是先收消息，反之亦然
            Scanner clientScanner = new Scanner(reader);
            while (clientScanner.hasNextLine()){
                //收到客户端消息
                String s = clientScanner.nextLine();
                System.out.println("收到客户端消息："+s);

                //服务端向客户端发消息
                String msg = scanner.next();
                System.out.println("服务端向客户端发消息："+msg);
                writer.println(msg);
                //在这里被坑到了，如果使用BufferedWriter 不加newline()和flush()的话，
                //服务端BufferedReader 的readline()方法就读取不到msg,会一直阻塞下去。
                //如果使用打印流PrintStream的话，就能避免上面遇到的麻烦了
                //writer.newLine();
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
